package metadata_tab

import (
	"strings"
	"time"

	"file_explorer/common/consts"
	"file_explorer/model"
	"file_explorer/service"
	"file_explorer/view/packed_widgets"
	"file_explorer/view/store"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"github.com/samber/lo"
)

type MetadataTabToolbar struct {
	*fyne.Container

	preview *MetadataPreview
	tabCtx  *store.MetadataTabContext
}

func (toolbar *MetadataTabToolbar) newLoadHistoryButton() *packed_widgets.MenuButton {
	preview := toolbar.preview
	historyButton := packed_widgets.NewMenuButton("还原", theme.HistoryIcon())

	metaFiles := service.GetMetaFiles(preview.tabCtx.Path)
	for _, metaFile := range metaFiles {
		name := metaFile.Name
		arr := strings.Split(name, ".")
		if len(arr) > 1 {
			key := arr[1]
			if createTime, err := time.Parse(consts.TimeLayoutWithoutMark, key); err == nil {
				name = createTime.Format(time.DateTime)
			}
		}
		historyButton.AddItem(
			name,
			metaFile,
			func(item interface{}) {
				metadata, err := service.ReadMetadata(item.(*model.FileInfo))
				if err != nil {
					return
				}

				if metadata.FilenameMap == nil {
					metadata.FilenameMap = make(map[string]*model.FileMetadata)
				}

				// 加载元数据
				for _, fileInfo := range preview.tabCtx.FileInfos {
					fileInfo.New.Metadata = &model.FileMetadata{}
					if metadata.FilenameMap[fileInfo.New.Name] != nil {
						fileInfo.New.Metadata = metadata.FilenameMap[fileInfo.New.Name]
					}
				}

				// 刷新视图
				preview.Table.Refresh()
			},
		)
	}

	return historyButton
}

func NewToolbar(preview *MetadataPreview) *MetadataTabToolbar {
	toolbar := &MetadataTabToolbar{
		preview: preview,
		tabCtx:  preview.tabCtx,
	}

	getData := func() []interface{} {
		return lo.Map(preview.tabCtx.FileInfos, func(item *model.ModifiedFileInfo, index int) interface{} {
			return item
		})
	}
	updateCtx := func(interfaces []interface{}) {
		preview.tabCtx.FileInfos = lo.Map(interfaces, func(item interface{}, index int) *model.ModifiedFileInfo {
			return item.(*model.ModifiedFileInfo)
		})
	}

	toolbar.Container = container.NewBorder(
		nil, nil,
		widget.NewToolbar(
			preview.Table.Checklist.GetMoveUpButton(getData, updateCtx),
			preview.Table.Checklist.GetMoveDownButton(getData, updateCtx),
			preview.Table.Checklist.GetMoveTopButton(getData, updateCtx),
			preview.Table.Checklist.GetMoveBottomButton(getData, updateCtx),
			widget.NewToolbarSeparator(),
			toolbar.newLoadHistoryButton(),
		),
		widget.NewToolbar(
			preview.Checklist.GetReverseButton(),
			preview.Checklist.GetRangeButton(),
		),
	)

	return toolbar
}
